package com.mo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mo.common.Result;
import com.mo.entity.PageVo;
import com.mo.entity.ParkingSpace;
import com.mo.service.ParkingSpaceService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController()
@RequestMapping("parking-space")
public class ParkingSpaceController {
    @Resource
    private ParkingSpaceService parkingSpaceService;

    @PostMapping
    @PreAuthorize("hasAuthority('sys:park:place:add')")
    public Result add(@RequestBody ParkingSpace parkingSpace) {
        boolean success = parkingSpaceService.save(parkingSpace);
        if (success) {
            return Result.success();
        }
        return Result.error();
    }

    @DeleteMapping
    @PreAuthorize("hasAuthority('sys:park:place:delete')")
    public Result delete(@RequestParam Integer id) {
        boolean success = parkingSpaceService.removeById(id);
        if (success) {
            return Result.success();
        }
        return Result.error();
    }

    @PutMapping
    @PreAuthorize("hasAuthority('sys:park:place:update')")
    public Result update(@RequestBody ParkingSpace parkingSpace) {
        boolean success = parkingSpaceService.updateById(parkingSpace);
        if (success) {
            return Result.success();
        }
        return Result.error();
    }

    @GetMapping
    public Result get(@RequestParam(required = false) String spaceNumber,
                      @RequestParam(required = false) String buildingLocation,
                      @RequestParam(required = false)  String floor,
                      @RequestParam(required = false)  String area,
                      @RequestParam Integer pageNum,
                      @RequestParam Integer pageSize) {

        LambdaQueryWrapper<ParkingSpace> wrapper = Wrappers.<ParkingSpace>lambdaQuery()
                .like(StringUtils.isNotBlank(spaceNumber), ParkingSpace::getSpaceNumber, spaceNumber)
                .like(StringUtils.isNotBlank(buildingLocation), ParkingSpace::getBuildingLocation, buildingLocation)
                .like(StringUtils.isNotBlank(floor), ParkingSpace::getFloor, floor)
                .like(StringUtils.isNotBlank(area), ParkingSpace::getArea, area)
                .orderByDesc(ParkingSpace::getLastUpdated);
        Page<ParkingSpace> page = parkingSpaceService.page(new Page<>(pageNum, pageSize), wrapper);
        PageVo<ParkingSpace> pagevo = new PageVo<>();
        pagevo.setTotal(page.getTotal());
        pagevo.setList(page.getRecords());
        pagevo.setPageSize(page.getSize());
        pagevo.setPageNum(page.getCurrent());

        return Result.success(pagevo);
    }
}
